﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using System.Collections;
using Microsoft.Xna.Framework;

namespace HelloXNA2.Component.MyCustom.DrawCircle
{
    public class PrimitiveLine
    {
        Texture2D pixel;
        ArrayList vectors;

        public Color Colour;

        public Vector2 Position;

        public float Depth;

        public int CountVectors
        {
            get { return vectors.Count; }
        }

        public PrimitiveLine(GraphicsDevice grahicsDevice)
        {
            pixel = new Texture2D(grahicsDevice, 1, 1, false, SurfaceFormat.Color);
            Color[] pixels = new Color[1];
            pixels[0] = Color.White;
            pixel.SetData<Color>(pixels);

            Colour = Color.White;
            Position = Vector2.Zero;
            Depth = 0;

            vectors = new ArrayList();
        }

        public void RemoveVector(Vector2 vector)
        {
            vectors.Remove(vector);
        }

        public void RemoveVector(int index)
        {
            vectors.RemoveAt(index);
        }

        public void ClearVectors()
        {
            vectors.Clear();
        }

        public void Render(SpriteBatch spriteBatch)
        {
            if (vectors.Count < 2)
                return;
            for (int i = 1; i < vectors.Count; i++)
            {
                Vector2 vector1 = (Vector2)vectors[i - 1];
                Vector2 vector2 = (Vector2)vectors[i];
                // calculate the distance between the two vectors
                float distance = Vector2.Distance(vector1, vector2);
                // calculate the angle between the two vectors
                float angle = (float)Math.Atan2((double)(vector2.Y - vector1.Y),
                    (double)(vector2.X - vector1.X));
                // stretch the pixel between the two vectors
                spriteBatch.Draw(pixel,
                    Position + vector1,
                    null,
                    Colour,
                    angle,
                    Vector2.Zero,
                    new Vector2(distance, 1),
                    SpriteEffects.None,
                    Depth);
            }
        }

        public void CreateCircle(float radius, int sides)
        {
            vectors.Clear();
            float max = 2 * (float)Math.PI;
            float step = max / (float)sides;
            for (float theta = 0; theta < max; theta += step)
            {
                vectors.Add(new Vector2(radius * (float)Math.Cos((double)theta),
                    radius * (float)Math.Sin((double)theta)));
            }
            // then add the first vector again so it's a complete loop
            vectors.Add(new Vector2(radius * (float)Math.Cos(0),
                radius * (float)Math.Sin(0)));
        }
    }
}
